package com.jse.api;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;

import com.jse.Strings;
import com.jse.Times;
import com.jse.json.Json;
import com.jse.json.JsonObject;

@SuppressWarnings("rawtypes")
public class AliPay {

	public static String m(Map param1) {
		JsonObject param=Json.jsonObject(param1);
		String privateKey=param.get("private_key").toString();
		String domain="https://openapi.alipay.com/gateway.do";
		String timestamp=Times.format();
		Map<String,String> dict=new HashMap<>();
		dict.put("app_id", param.getString("app_id"));
		dict.put("method", "alipay.trade.wap.pay");//手机
		dict.put("return_url", param.getString("return_url"));
		dict.put("enc", "utf-8");
		dict.put("charset", "utf-8");
		dict.put("sign_type", "RSA2");
		dict.put("timestamp", timestamp);
		dict.put("version", "1.0");
		dict.put("notify_url", param.getString("notify_url"));
		String biz_content="{\"out_trade_no\":\""+param.get("orderno")+"\"," 
				+ "\"total_amount\":\""+ param.get("price") +"\"," 
				+ "\"subject\":\""+param.get("title")+"\"," 
				+ "\"quit_url\":\""+param.get("quit_url")+"\"," //用户付款中途退出返回商户网站的地址
				+ "\"body\":\""+Objects.requireNonNullElse(param.get("body"), param.get("title"))+"\"," 
				+ "\"product_code\":\"QUICK_WAP_WAY\"}";
		dict.put("biz_content", biz_content);
		String content=Ali.getSignatureContent(dict);//待签名字符串
		String sign=Ali.rsaSign(content,
				privateKey,"utf-8","RSA2");
		dict.put("sign",sign);
		String ps=buildQuery(dict,StandardCharsets.UTF_8);
		return domain+"?"+ps;
	}
	public static String qrcode(Map param1) {
		JsonObject param=Json.jsonObject(param1);
		String privateKey=param.get("private_key").toString();
		String domain="https://openapi.alipay.com/gateway.do";
		String timestamp=Times.format();
		Map<String,String> dict=new HashMap<>();
		dict.put("app_id", param.getString("app_id"));
		dict.put("method", "alipay.trade.precreate");//手机
		dict.put("notify_url", param.getString("notify_url"));
		dict.put("charset", "utf-8");
		dict.put("sign_type", "RSA2");
		dict.put("timestamp", timestamp);
		dict.put("version", "1.0");
		String biz_content="{\"out_trade_no\":\""+param.get("orderno")+"\"," 
				+ "\"total_amount\":\""+ param.get("price") +"\"," 
				+ "\"subject\":\""+param.get("title")+"\"," 
				+ "\"body\":\""+Objects.requireNonNullElse(param.get("body"), param.get("title"))+"\"}";
		dict.put("biz_content", biz_content);
		String content=Ali.getSignatureContent(dict);//待签名字符串
		String sign=Ali.rsaSign(content,
				privateKey,"utf-8","RSA2");
		dict.put("sign",sign);
		String ps=buildQuery(dict,StandardCharsets.UTF_8);
		return domain+"?"+ps;
	}
	
	public static String pc(Map param1) {
		JsonObject param=Json.jsonObject(param1);
		String privateKey=param.getString("private_key");
		String domain="https://openapi.alipay.com/gateway.do";
		String timestamp=Times.format();
		Map<String,String> dict=new HashMap<>();
		dict.put("app_id", param.getString("app_id"));
		dict.put("method", "alipay.trade.page.pay");//pc
		dict.put("return_url", param.getString("return_url"));
		dict.put("charset", "utf-8");
		dict.put("sign_type", "RSA2");
		dict.put("timestamp", timestamp);
		dict.put("version", "1.0");
		dict.put("notify_url", param.getString("notify_url"));
		String biz_content="{\"out_trade_no\":\""+param.get("orderno")+"\"," 
				+ "\"total_amount\":\""+ param.get("price") +"\"," 
				+ "\"subject\":\""+param.get("title")+"\"," 
				+ "\"body\":\""+Objects.requireNonNullElse(param.get("body"), param.get("title"))+"\"," //可选
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
		dict.put("biz_content", biz_content);
		String content=Ali.getSignatureContent(dict);//待签名字符串
		String sign=Ali.rsaSign(content,
				privateKey,"utf-8","RSA2");
		dict.put("sign",sign);
		String ps=buildQuery(dict,StandardCharsets.UTF_8);
		return domain+"?"+ps;
	}
	
	public static String pay(Map param) {
		if(param.containsKey("store_id")) {
			return qrcode(param);
		}else if(param.containsKey("quit_url")) {
			return m(param);
		}else {
			return pc(param);
		}
	}
	
	public static void main(String[] args) throws IOException {
		String private_key="MIIEvgIBADAN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y8e8QKBgQCK8bE4lK3x829n2j/CngkSvLAsbXQvRyspKeLEgHcwCmZJBvWBOQZZPDNk8mSW3QZUmsintrR87pcTUG8+5VU6XaU48LtwBRakeOZbF+wcvbFONk37oR2rLej4mYXnR0muQkmH/V+xvZyxE73N5mtYPaLz5z8xSQk7dDCnb+jurQKBgHobbgm/W+8/My6uzQC+vWrtvC7xTdlZX3Hwh77w3mE4GDnbWmQnqwMuZ93m7coilaqXIWlkGke/tELGUCbcTKjspUTfBA4eSTyU64CtZ74f0WpFFd7WHxuWK83oheoqcSkl7hC1+mWzyktpmuKy5nwTqfQt1cPI4RHlSmQaVPUBAoGBALgkhbTEVT+pbh+7EmODrdr2jKVtEkg0szn7Jy/65wonL3Gz3EGujvhDagn5YX1gQUAEfSmy1SjXzAk1EGbLKmUr8P1ztrVz507c3EtEbiWb3EC72QO/24fBVJcOZAakgYkwyH/ZOgXquaZa2nEnDsbxS1FphY8dnbVo5aR0Yfn0";
		Map<String,String> dict=new HashMap<>();
		dict.put("private_key", private_key);
		dict.put("app_id", "2017082208324227");
//		dict.put("quit_url", "http://www.baidu.com");//手机必加 别的一样
		dict.put("return_url", "http://www.iepsy.com/pay/alipay/return_url");
		dict.put("notify_url", "http://www.iepsy.com/pay/alipay/notify_url");
		dict.put("orderno", "2017082208324227");
		dict.put("price", "0.01");
		dict.put("title", "2019test");
		System.err.println(pay(dict));
	}

    public static String buildQuery(Map<String, String> params,Charset charset) {
        if (params == null || params.isEmpty()) {
            return null;
        }
        StringBuilder query = new StringBuilder();
        Set<Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;
        for (Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            // 忽略参数名或参数值为空的参数
            if (!Strings.isEmpty(name)&&!Strings.isEmpty(value)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }
                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }
        return query.toString();
    }
}
